﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;

namespace SdmxMailNotifier
{
    /// <summary>
    /// This class implements the properties of a users. The properties of a user defines the period with which notifications are sent to the user, 
    /// and the date when the last notification has been sent. The user properties also specifies the interest of the users which are specified using four patterns: 
    ///    1) for groups, 2) for artefact types, 3) for artefact identifiers, and 4) for versions
    /// </summary>
    public class User : DataTable
    {
        #region Constants

        // Constants for the inscription columns
        private const string AGENCY_PATTERN_COLUMN_NAME = "AGENCY";
        private const string TYPE_PATTERN_COLUMN_NAME = "TYPE";
        private const string ARTEFACT_PATTERN_COLUMN_NAME = "ARTEFACT";
        private const string VERSION_PATTERN_COLUMN_NAME = "VERSION";
        private const string MODIFICATION_PATTERN_COLUMN_NAME = "MODIFICATION";

        // Constants for the properties related to user notification
        private const string MAIL_ADDRESS_PROPERTY_NAME = "Mail";
        private const string PERIOD_PROPERTY_NAME = "Period";
        private const string LAST_NOTIFICATION_PROPERTY_NAME = "LastNotification";

        // Constants for periods
        private static TimeSpan DEFAULT_PERIOD = new TimeSpan(7, 0, 0, 0); // One week
        private static TimeSpan TIME_EPSILON = new TimeSpan(2, 0, 0); // Two hours 

        #endregion

        #region Constructors
        public User(string username, FileInfo userConfigurationFile)
            : base(username)
        {
            if (userConfigurationFile.Exists)
            {
                this.ReadXml(userConfigurationFile.FullName);
            }
            else
            {
                Init("", DEFAULT_PERIOD);
            }
        }

        private void Init(string mail, TimeSpan period)
        {
            this.Columns.Add(new DataColumn(AGENCY_PATTERN_COLUMN_NAME, typeof(string)));
            this.Columns.Add(new DataColumn(TYPE_PATTERN_COLUMN_NAME, typeof(string)));
            this.Columns.Add(new DataColumn(ARTEFACT_PATTERN_COLUMN_NAME, typeof(string)));
            this.Columns.Add(new DataColumn(VERSION_PATTERN_COLUMN_NAME, typeof(string)));
            this.Columns.Add(new DataColumn(MODIFICATION_PATTERN_COLUMN_NAME, typeof(string)));

            base.ExtendedProperties.Add(PERIOD_PROPERTY_NAME, period.ToString());
            base.ExtendedProperties.Add(LAST_NOTIFICATION_PROPERTY_NAME, DateTime.Now.ToString());
            base.ExtendedProperties.Add(MAIL_ADDRESS_PROPERTY_NAME, mail);
        }

        #endregion

        #region Subscription Management
        public void setSubscriptions(DataTable subscriptions)
        {
            this.Rows.Clear();
            foreach (DataRow row in subscriptions.Rows)
            {
                this.Rows.Add(row.ItemArray);
            }
        }
        
        private bool IsArtefactInteresting(string agency, string artefactType, string id, string version)
        {
            bool result = false;

            foreach (DataRow row in base.Rows)
            {
                result = result || (Regex.IsMatch (agency, (string) row[AGENCY_PATTERN_COLUMN_NAME]) && Regex.IsMatch (artefactType, (string) row[TYPE_PATTERN_COLUMN_NAME]) && Regex.IsMatch (id, (string) row[ARTEFACT_PATTERN_COLUMN_NAME]) && Regex.IsMatch (version, (string) row[VERSION_PATTERN_COLUMN_NAME]));
            }

            return result;
        }

        // TODO this method should be executed on the side of the artefact list
        public DataSet GetInterestingArtefacts(DataSet artefacts)
        {
            DataSet result = new DataSet();

            foreach (DataTable table in artefacts.Tables)
            {
                string artefactType = table.TableName;
                DataTable resultTable = table.Clone();
                foreach (DataRow row in table.Rows)
                {
                    string agency = row["AI"].ToString();
                    string id = row["ID"].ToString();
                    string version = row["VER"].ToString();

                    // TODO possibly interpret modifications
                    DateTime lastUpdate = DateTime.Parse(row["LU"].ToString());
                    DateTime creation = DateTime.Parse(row["CR"].ToString());

                    if (IsArtefactInteresting(agency, artefactType, id, version))
                    {
                        resultTable.Rows.Add(row.ItemArray);
                    }
                }
                if (resultTable.Rows.Count > 0)
                {
                    result.Tables.Add(resultTable);
                }
            }

            return result;
        }
        #endregion

        #region Periodical Notification Management
        public bool MustBeNotified(DateTime notificationTime)
        {
            TimeSpan period = TimeSpan.Parse((string)base.ExtendedProperties[PERIOD_PROPERTY_NAME]);

            return (notificationTime + TIME_EPSILON - GetLastUpdate() > period);
        }

        public DateTime GetLastUpdate()
        {
            string lastUpdate = (string)base.ExtendedProperties[LAST_NOTIFICATION_PROPERTY_NAME];

            return DateTime.Parse(lastUpdate);
        }

        public void SignalNotification(DateTime notificationTime)
        {
            base.ExtendedProperties[LAST_NOTIFICATION_PROPERTY_NAME] = notificationTime.ToString();
        }

        public void SetPeriod(TimeSpan period)
        {
            base.ExtendedProperties[PERIOD_PROPERTY_NAME] = period.ToString();
        }

        public string GetMailAddress()
        {
            return base.ExtendedProperties[MAIL_ADDRESS_PROPERTY_NAME].ToString();
        }

        public void SetMailAddress(string mailAddress)
        {
            base.ExtendedProperties[MAIL_ADDRESS_PROPERTY_NAME] = mailAddress;
        }

        #endregion
    }

    /// <summary>
    /// This class implements the access to the complete configuration of the web service
    /// </summary>
    public class UsersManager
    {
        #region Constants
        // Constants defining how user configuration file are saved        
        private const string USER_CONFIGURATION_EXTENSION = "xml";
        private static string[] FORBIDDEN_CHARS_IN_USERNAME = {"\\", "/", ":", "*", "?", "\"", "<", ">", "|" };
        private static Regex USER_CONFIGURATION_FILE_REGEX = new Regex("(.*)\\.xml");
        #endregion

        #region (Internal and External) Members
        private DirectoryInfo usersDirectory;
        private List<string> loadedUsers = new List<string>();
        #endregion

        #region Constructor
        public UsersManager(DirectoryInfo usersDirectory)
            : base()
        {
            this.usersDirectory = usersDirectory;
            if (!this.usersDirectory.Exists)
            {
                this.usersDirectory.Create();
            }
        }
        #endregion

        #region User Management
        private string NormalizeUsername(string username)
        {
            string result = username;
            foreach (string forbiddenChar in FORBIDDEN_CHARS_IN_USERNAME)
            {
                result = result.Replace(forbiddenChar, "_");
            }
            return result;
        }

        private FileInfo GetUserConfigurationFile(string username)
        {
            return new FileInfo(Path.Combine(this.usersDirectory.FullName, username + "." + USER_CONFIGURATION_EXTENSION));
        }

        public List<string> GetAllUsers()
        {
            List<string> result = new List<string>();

            foreach (FileInfo userFile in this.usersDirectory.GetFiles("*." + USER_CONFIGURATION_EXTENSION, SearchOption.AllDirectories))
            {
                Match match = USER_CONFIGURATION_FILE_REGEX.Match(userFile.Name);
                if (match.Success)
                {
                    result.Add(match.Groups[1].Value);
                }
            }

            return result;
        }

        public User LoadUser(string username, bool mustBeLocked)
        {
            string normalizedUsername = NormalizeUsername(username);

            lock (this)
            {
                if (!loadedUsers.Contains(normalizedUsername))
                {
                    if (mustBeLocked)
                    {
                        loadedUsers.Add(normalizedUsername);
                    }
                    return new User(normalizedUsername, GetUserConfigurationFile(normalizedUsername));
                }
                else
                {
                    return null;
                }
            }
        }

        // TODO think on how protect the concurrency access to the users
        public void ReleaseUser(User user)
        {
            String username = user.TableName;

            user.WriteXml(GetUserConfigurationFile(username).FullName, XmlWriteMode.WriteSchema, true);
            lock (this)
            {
                loadedUsers.Remove(username);
            }
        }
        #endregion
    }
}